package com.liuzhilin.service;

import com.liuzhilin.domain.Article;
import com.liuzhilin.domain.Comment;
import com.liuzhilin.domain.Manager;
import com.liuzhilin.domain.User;
import com.liuzhilin.mapper.DatabaseOperations;
import com.liuzhilin.mapper.DatabaseSQl;
import com.liuzhilin.util.BCryptService;
import com.mysql.cj.protocol.Resultset;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Set;
/*
* 用户服务类
* */
public class UserService {
    // 用户登录
    public static boolean userLogin(String userName, String password) {
        String realPassword = passwordSelect(userName);
        if (realPassword == null) {
            return false;
        }
        // 密码校验
        if (BCryptService.checkPassword(password, realPassword)) {
            return true;
        } else {
            return false;
        }
    }

    // 用户名查询用户密码
    public static String passwordSelect(String username) {
        Object[] objects = {username};
        ResultSet resultSet = DatabaseOperations.executeQuery(DatabaseSQl.userNameSql(), objects);
        try {
            // 判断用户名是否存在
            if (resultSet.next()) {
                return resultSet.getString("password");
            } else {
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    //查询用户是否存在
    public static boolean usernameExists(String username) {
        Object[] objects = {username};
        ResultSet resultSet = DatabaseOperations.executeQuery(DatabaseSQl.userNameSql(), objects);
        try {
            // 判断用户名是否存在
            if (resultSet.next()) {
                return true;
            } else {
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 注册用户
    public static String userRegister(String userName, String password, String personalSignature, String birthday) {
        // 检验用户名是否存在
        if (usernameExists(userName)) {
            return "用户名已存在！";
        }
        // 检验用户名是否合法
        if (userName.length() > 20) {
            return "用户名长度不能超过20个字符！";
        }
        //检验密码是否合法
        if (!password.matches("^(?=.*[0-9])(?=.*[a-zA-Z]).{4,}$")) {
            return "密码不规范！";
        }
        // 对密码进行加密
        password = BCryptService.encryptPassword(password);
        //检验生日是否合法
        try {
            Date.valueOf(birthday);
        } catch (IllegalArgumentException e) {
            return "生日不规范!";
        }
        Date date = Date.valueOf(birthday);
        if (date.after(new Date(System.currentTimeMillis()))) {
            return "生日不规范!";
        }
        Object[] objects = {userName, password, personalSignature, date};
        DatabaseOperations.executeUpdate(DatabaseSQl.userRegisterSql(), objects);
        return "注册成功！";
    }

    // 查询用户信息
    public static User userInformationSelect(String userName) {
        userName  = userName.trim();
        Object[] objects = {userName};
        ResultSet resultSet = DatabaseOperations.executeQuery(DatabaseSQl.userNameSql(), objects);
        //将查询到的用户信息封装到User对象中
        try {
            if (resultSet.next()) {
                return new User(resultSet.getInt("id"),
                        resultSet.getString("userName"),
                        resultSet.getString("password"),
                        resultSet.getString("personalSignature"),
                        resultSet.getInt("articleCount"),
                        resultSet.getDate("birthday"),
                        resultSet.getInt("status")
                );
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }
    //获取所有文章信息
    public static List<Article> getArticles(String category){
        List<Article> articles = new ArrayList<>();
        ResultSet resultSet=null;
        if(category.equals("所有博客")){
            resultSet = DatabaseOperations.executeQuery(DatabaseSQl.allArticleSql(),null);
        }else{
            Object[] objects = {category};
            resultSet = DatabaseOperations.executeQuery(DatabaseSQl.articleSql(),objects);
        }

        Date today = new Date(System.currentTimeMillis());
        try {
            while (resultSet.next()) {
                int status = resultSet.getInt("status");
                //将文章的日期转为Date对象
                Date publishTime = Date.valueOf(resultSet.getString("publishTime"));
                if (publishTime.after(today)) {
                    continue;
                }
                if (status == 1) {
                    Article article = new Article(
                            resultSet.getString("writer"),
                            resultSet.getString("title"),
                            resultSet.getString("content"),
                            resultSet.getString("publishTime"),
                            resultSet.getString("category"),
                            resultSet.getInt("status"),
                            resultSet.getInt("like"),
                            resultSet.getInt("comment"),
                            resultSet.getInt("favorite")
                    );
                    articles.add(article);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return articles;
    }
    //修改用户信息
    public static boolean modifyUserInformation(String userName,String personalSignature,String birthday) {
        // 检验生日是否合法
        try {
            Date.valueOf(birthday);
        } catch (IllegalArgumentException e) {
            return false;
        }
        Date date = Date.valueOf(birthday);
        // 检验生日是否在当前时间之前
        if (date.after(new Date(System.currentTimeMillis()))) {
            return false;
        }
        Object[] objects = {personalSignature,date,userName};
        DatabaseOperations.executeUpdate(DatabaseSQl.modifyUserInformationSql(),objects);
        return true;
    }
    //根据分区得到对应编号
    public static int getCategoryId(String category){
        if (category.equals("游戏区")) {
            return 1;
        } else if (category.equals("科技区")) {
            return 2;
        } else if (category.equals("体育区")) {
            return 3;
        } else if (category.equals("军事区")) {
            return 4;
        } else if (category.equals("农业区")) {
            return 5;
        } else {
            return 0;
        }
    }
    //上传博客
    public static boolean uploadArticle(String userName,String title,String content,String category,String publishTime){
        int categoryId = getCategoryId(category);
        //查询用户的状态
        int status = userInformationSelect(userName).getStatus();
        if (status==7){
            return false;
        }else if (status==categoryId){
            return false;
        }
        publishTime = publishTime.substring(0,10);
        Date date = Date.valueOf(publishTime);
        userName=userName.trim();
        Object[] objects = {userName,title,content,date,category};
        try {
            DatabaseOperations.executeUpdate(DatabaseSQl.uploadArticleSql(),objects);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
    //对用户的点赞收藏评论进行操作
    public static String feedback(String writer,String title,String currentUsername,Integer statusStr,String comment){
        //将状态转换为数字,直接转
        int status = statusStr;
        currentUsername = currentUsername.trim();
        String result = selectFeedback(writer,title,currentUsername,status);
        if (!result.equals("没有记录")){
            return result;
        }
        //查询文章
        Object[] objects = {writer,title};
        ResultSet resultSet = DatabaseOperations.executeQuery(DatabaseSQl.singleArticleSql(),objects);
        Article article= null;
        try {
            if (resultSet.next()) {
                //保存文章信息到文章对象中
                article = new Article(
                        resultSet.getString("writer"),
                        resultSet.getString("title"),
                        resultSet.getString("content"),
                        resultSet.getString("publishTime"),
                        resultSet.getString("category"),
                        resultSet.getInt("status"),
                        resultSet.getInt("like"),
                        resultSet.getInt("comment"),
                        resultSet.getInt("favorite")
                );
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        //将该文章对象的状态设置为status
        article.setStatus(status);
        //将文章对象中的信息更新到数据库中
        Object[] objects1 = {article.getWriter(),article.getTitle(),article.getContent(),article.getPublishTime(),article.getCategory(),currentUsername,article.getStatus(),article.getLike(),article.getComment(),article.getFavorite()};
        try{
            DatabaseOperations.executeUpdate(DatabaseSQl.feedbackSql(),objects1);
        }catch (Exception e){
            e.printStackTrace();
        }
        //根据状态进行点赞，收藏，评论结果返回
        if (status==2){
            int like =article.getLike();
            like = like+1;
            article.setLike(like);
            result="点赞成功";
        }
        if (status==3){
            int commentCount =article.getComment();
            commentCount = commentCount+1;
            article.setComment(commentCount);
            Object[] objects3 = {article.getWriter(),article.getTitle(),currentUsername,comment};
            DatabaseOperations.executeUpdate(DatabaseSQl.uploadCommentSql(),objects3);
            result="评论成功";
        }
        if (status==4){
            int favorite =article.getFavorite();
            favorite = favorite+1;
            article.setFavorite(favorite);
            result="收藏成功";
        }
        //更新数据库中该文章的点赞，收藏，评论的数量
        Object[] objects2 = {article.getLike(),article.getComment(),article.getFavorite(),article.getWriter(),article.getTitle(),article.getCategory()};
        try{
            DatabaseOperations.executeUpdate(DatabaseSQl.updateFeedbackSql(),objects2);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
    //查询用户是否已经点赞，收藏，防止重复点赞，收藏
    public static String selectFeedback(String writer,String title,String currentUsername,int status){
        String result="没有记录";
        Object[] objects = {writer,title,currentUsername,status};
        try {
            //获取查询结果
            ResultSet resultSet = DatabaseOperations.executeQuery(DatabaseSQl.selectFeedbackSql(),objects);
            if(resultSet.next()){
                if (resultSet.getInt("status")==status && status==2){
                    result="您已经点赞过了";
                } else if (resultSet.getInt("status")==status && status==4){
                    result="您已经收藏过了";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
    //获取文章的评论
    public static List<Comment> getComments(String writer, String title){
        List<Comment> comments = new ArrayList<>();
        Object[] objects = {writer,title};
        ResultSet resultSet = DatabaseOperations.executeQuery(DatabaseSQl.selectCommentSql(),objects);
        try {
            while (resultSet.next()){
                Comment comment = new Comment(
                        resultSet.getString("comment"),
                        resultSet.getString("reader")
                );
                comments.add(comment);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return comments;
    }
    //获取用户个人中心文章
    public static List<Article> getUserProfileArticles(String username, String type) {
        List<Article> articles = new ArrayList<>();
        int status = 0;
        if (type.equals("myBlogs")) {
            status = 1;
        } else if (type.equals("myFavorites")) {
            status = 4;
        } else if (type.equals("myLikes")) {
            status = 2;
        }else if(type.equals("myBrowsed")){
            status = 5;
        } else {
            status = 3;
        }
        Object[] objects = {username, status};
        //设置一个集合，用于存储文章的唯一标识，以避免重复添加
        Set<String> uniqueArticleKeys = new HashSet<>();

        try {
            ResultSet resultSet = null;
            if (status == 1) {
                // 查询用户自己的文章
                resultSet = DatabaseOperations.executeQuery(DatabaseSQl.selectUserStatusArticleSql(), objects);
            } else if (status == 4 || status == 2 || status == 3 || status == 5) {
                // 查询用户收藏，点赞，评论的文章
                resultSet = DatabaseOperations.executeQuery(DatabaseSQl.selectUserProfileArticleSql(), objects);
            }

            while (resultSet.next()) {
                // 使用文章的标题、作者和发布时间作为唯一标识
                String articleKey = resultSet.getString("title") + "-" + resultSet.getString("writer") + "-" + resultSet.getString("publishTime");

                if (!uniqueArticleKeys.contains(articleKey)) {
                    Article article = new Article(
                            resultSet.getString("writer"),
                            resultSet.getString("title"),
                            resultSet.getString("content"),
                            resultSet.getString("publishTime"),
                            resultSet.getString("category"),
                            resultSet.getInt("status"),
                            resultSet.getInt("like"),
                            resultSet.getInt("comment"),
                            resultSet.getInt("favorite")
                    );
                    articles.add(article);
                    uniqueArticleKeys.add(articleKey);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return articles;
    }
    //根据搜索内容查询文章
    public  static List<Article> getSelectArticles(String query,String category) {
        List<Article> articles = new ArrayList<>();
        ResultSet resultSet = null;
        try {
            Object[] objects = {query,query,query};
            resultSet = DatabaseOperations.executeQuery(DatabaseSQl.selectArticleByQuerySql(),objects);
            }
        catch (Exception e){
            e.printStackTrace();
        }
        try {
            while (resultSet.next()) {
                Article article = new Article(
                        resultSet.getString("writer"),
                        resultSet.getString("title"),
                        resultSet.getString("content"),
                        resultSet.getString("publishTime"),
                        resultSet.getString("category"),
                        resultSet.getInt("status"),
                        resultSet.getInt("like"),
                        resultSet.getInt("comment"),
                        resultSet.getInt("favorite")
                );
                if (category.equals("所有博客")){
                    articles.add(article);
                }else if (article.getCategory().equals(category)){
                    articles.add(article);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("搜索成功");
        System.out.println(articles);
        return articles;
    }
    //根据用户状态匹配封禁类型
    public static String userStatus(int status){
        String result="";
        switch (status){
            case 1:
                result="游戏区封禁";
                break;
            case 2:
                result="科技区封禁";
                break;
            case 3:
                result="体育区封禁";
                break;
            case 4:
                result="军事区封禁";
                break;
            case 5:
                result="农业区封禁";
                break;
            case 6:
                result="艺术区封禁";
                break;
            case 7:
                result="全区封禁";
                break;
            default:
                result="正常";
        }
        return result;

    }
    //获取未审核文章
    public static List<Article> getUnapprovedArticles(String userName){
        List<Article> articles = new ArrayList<>();
        try {
            ResultSet resultSet = DatabaseOperations.executeQuery(DatabaseSQl.selectUnapprovedArticleSql(),new Object[]{userName});
            while (resultSet.next()) {
                Article article = new Article(
                        resultSet.getString("writer"),
                        resultSet.getString("title"),
                        resultSet.getString("content"),
                        resultSet.getString("publishTime"),
                        resultSet.getString("category"),
                        resultSet.getInt("status"),
                        resultSet.getInt("like"),
                        resultSet.getInt("comment"),
                        resultSet.getInt("favorite")
                );
                articles.add(article);
            }
        }catch (Exception e){
            e.printStackTrace();
            return articles;
        }
        return articles;
    }
    //修改文章内容
    public static boolean modifyArticle(String writer,String title,String content,String category){
        //更新文章内容
        try {
            DatabaseOperations.executeUpdate(DatabaseSQl.modifyArticleSql(),new Object[]{content,writer,title,category});
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        //更新文章状态
        try {
            DatabaseOperations.executeUpdate(DatabaseSQl.modifyArticleStatusSql(),new Object[]{writer,title,category});
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

    }
    //记录用户浏览记录
    public static String recordArticleBrowse(String writer,String category,String title,String userName){
        //status为5表示用户浏览记录
        int status = 5;
        userName=userName.trim();
        Object[] objects = {writer,title};
        ResultSet resultSet = DatabaseOperations.executeQuery(DatabaseSQl.singleArticleSql(),objects);
        Article article= null;
        try {
            if (resultSet.next()) {
                //保存文章信息到文章对象中
                article = new Article(
                        resultSet.getString("writer"),
                        resultSet.getString("title"),
                        resultSet.getString("content"),
                        resultSet.getString("publishTime"),
                        resultSet.getString("category"),
                        resultSet.getInt("status"),
                        resultSet.getInt("like"),
                        resultSet.getInt("comment"),
                        resultSet.getInt("favorite")
                );
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        //将该文章对象的状态设置为status
        article.setStatus(status);
        //将文章对象中的信息更新到数据库中
        Object[] objects1 = {article.getWriter(),article.getTitle(),article.getContent(),article.getPublishTime(),article.getCategory(),userName,article.getStatus(),article.getLike(),article.getComment(),article.getFavorite()};
        try{
            DatabaseOperations.executeUpdate(DatabaseSQl.feedbackSql(),objects1);
            return "记录成功";
        }catch (Exception e){
            e.printStackTrace();
            return "记录失败";
        }
    }
    //保存申诉内容
    public static boolean saveAppealToDatabase(String username,String appealTarget,String content){
        //记录现在时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        appealTarget=appealTarget+"管理员";
        username=username.trim();
        content="申诉对象:"+appealTarget+" 内容:"+ content;
        String Manager="superManager";
        int type=0;
        try{
            DatabaseOperations.executeUpdate(DatabaseSQl.recordOperationLogSql(),new Object[]{username,Manager,content,type,formattedDateTime});
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
    //保存举报内容
    public static boolean saveReportToDatabase( String reporter, String writer, String title, String category, String reportContent){
        reporter=reporter.trim();
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        String manager=getManagerByCategory(category);
        reportContent="被举报对象:"+writer+" 文章标题:"+title+" 分区:"+category+" 内容:"+reportContent;
        int type=0;
        try{
            DatabaseOperations.executeUpdate(DatabaseSQl.recordOperationLogSql(),new Object[]{reporter,manager,reportContent,type,formattedDateTime});
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

    }
    //根据分区判断管理员
    public static String getManagerByCategory(String category){
        String manager = null;
        switch (category){
            case "游戏区":
                manager="first";
                break;
            case "科技区":
                manager="secend";
                break;
            case "体育区":
                manager="third";
                break;
            case "军事区":
                manager="fourth";
                break;
            case "农业区":
                manager="fifth";
                break;
            case  "艺术区":
                manager="sixth";
                break;
        }
        manager=manager+"Manager";
        return manager;
    }



}
